package com.example.origin.finance.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.example.origin.finance.dto.BaseTable;
import com.example.origin.finance.dto.XueqiuIndicator;
import com.example.origin.finance.dto.XueqiuQuote;
import com.example.origin.finance.enums.AnalystEnum;
import com.example.origin.finance.enums.TableNameEnum;
import com.example.origin.finance.trade.service.impl.AlphaModelService;
import com.example.origin.finance.trade.service.impl.BetaModelService;
import com.example.origin.finance.utils.CalcUtil;
import io.swagger.models.auth.In;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.util.Pair;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("trade")
@RestController
public class TradeController {


    @Resource
    private AlphaModelService alphaModelService;

    @Resource
    private BetaModelService betaModelService;


    @SneakyThrows
    @GetMapping("statQuote")
    public String statQuote() {
        Query query = new Query();
        query.addCriteria(Criteria.where("peTtm").gt(5).lt(50));
        query.addCriteria(Criteria.where("dividendYield").gt(0));
        query.addCriteria(Criteria.where("marketCapital").gt(0.2E11));
        List<XueqiuQuote> quoteList = find(query, TableNameEnum.XUEQIU_GUPIAO_QUOTE);
        log.info("size:{}", quoteList.size());
        quoteList.stream().map(e -> {
            HashMap<Object, Object> left = new HashMap<>();
            // 股息占盈利的比值
            left.put("pd", CalcUtil.multiply(e.getDividendYield() / 100, 100 / e.getPeTtm()).doubleValue());
            return Pair.of(left, e);
        }).sorted(Comparator.comparing(a -> {
            Object o = a.getFirst().get("pd");
            return Double.parseDouble(o.toString());
        }, Comparator.reverseOrder())).limit(1000).forEach(a -> {
            HashMap<Object, Object> left = a.getFirst();
            XueqiuQuote e = a.getSecond();
            log.info("{}-{}-{}-gxl:{}-pe:{}-{}-{}", e.getCode(), e.getName(), left.get("pd"), e.getDividendYield(), e.getPeTtm(), e.getMarketCapital() / 1E8, JSONUtil.toJsonStr(e));
        });
        return "end";

    }

    private <T> List<T> find(Query query, TableNameEnum tableNameEnum) {
        return alphaModelService.find(query, tableNameEnum);
    }

    @SneakyThrows
    @GetMapping("statIndicator")
    public void statIndicator(@RequestParam(defaultValue = "2023-01-01") String nowStr, @RequestParam(defaultValue = "2024-01-01") String endStr) {
        DateTime now = DateUtil.parseDate(nowStr);
        DateTime end = DateUtil.parseDate(endStr);
        Query query = new Query();
        query.addCriteria(Criteria.where("reportDate").gte(now).lt(end));

        List<XueqiuQuote> quoteList = find(new Query(), TableNameEnum.XUEQIU_GUPIAO_QUOTE);
        Map<String, XueqiuQuote> quoteMap = quoteList.stream().collect(Collectors.toMap(BaseTable::getCode, e -> e));

        List<XueqiuIndicator> xueqiuIndicators = find(query, TableNameEnum.XUEQIU_GUPIAO_INDICATOR);
        Map<String, XueqiuIndicator> xueqiuIndicatorMap = xueqiuIndicators.stream().collect(Collectors.toMap(BaseTable::getCode, e -> e, (a, b) -> {
            if (a.getCtime().getTime() > b.getCtime().getTime()) {
                return a;
            }
            return b;
        }));
        log.info("size:{}", xueqiuIndicatorMap.size());
        xueqiuIndicatorMap.values().stream().filter(e -> e.getRop() > 100 && e.getAvgRoe() > 10).sorted(Comparator.comparing(XueqiuIndicator::getRop, Comparator.reverseOrder()).thenComparing(XueqiuIndicator::getAvgRoe, Comparator.reverseOrder())).forEach(e -> {
            XueqiuQuote xueqiuQuote = quoteMap.get(e.getCode());
            if (xueqiuQuote != null) {
                log.info("{}-{}-{}-rop:{}-roe:{}-{}", e.getCode(), xueqiuQuote.getName(), e.getReportName(), e.getRop(), e.getAvgRoe(), JSONUtil.toJsonStr(e));
            }
        });
    }

    @SneakyThrows
    @GetMapping("alphaModel")
    public String alphaModel(@RequestParam(defaultValue = "2023-01-01") String nowStr, @RequestParam(defaultValue = "2024-01-01") String endStr) {
        alphaModelService.model(nowStr, endStr);
        return "end";
    }

    @GetMapping("betaModel")
    public String betaModel(@RequestParam(defaultValue = "1") Integer model, @RequestParam(defaultValue = "2023-01-01") String nowStr, @RequestParam(defaultValue = "2024-12-01") String endStr) {
        AnalystEnum analystEnum = AnalystEnum.get(model);
        switch (analystEnum){
            case RED_ANALYST:
                betaModelService.model(nowStr, endStr,AnalystEnum.RED_ANALYST);
                break;
            default:
                break;
        }
        return "end";
    }

    @GetMapping("betaModelUs")
    public String betaModelUs(@RequestParam(defaultValue = "2") Integer model, @RequestParam(defaultValue = "2023-01-01") String nowStr, @RequestParam(defaultValue = "2024-12-01") String endStr) {
        AnalystEnum analystEnum = AnalystEnum.get(model);
        switch (analystEnum){
            case RED_US_ANALYST:
                betaModelService.model(nowStr, endStr,AnalystEnum.RED_US_ANALYST);
                break;
            case RED_US_JIJIN_ANALYST:
                betaModelService.model(nowStr, endStr,AnalystEnum.RED_US_JIJIN_ANALYST);
                break;
            default:
                break;
        }
        return "end";
    }



}
